package cn.edu.zut.hhr.aspect;

import cn.edu.zut.hhr.annotation.CacheAnnotation;
import cn.edu.zut.hhr.controller.ArticleController;
import cn.edu.zut.hhr.entity.User;
import cn.edu.zut.hhr.utils.MD5Util;
import cn.edu.zut.hhr.utils.RedisUtil;
import cn.edu.zut.hhr.utils.StatisticsUtil;
import cn.edu.zut.hhr.utils.UserUtil;
import cn.edu.zut.hhr.vo.RestResponse;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;

@Component
@Aspect
public class CacheAspectJ {

    @Resource
    RedisUtil redisUtil;

    @Pointcut("@annotation(cn.edu.zut.hhr.annotation.CacheAnnotation)")
    private void pointCut(){};

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Object[] paramObjects = joinPoint.getArgs();
        CacheAnnotation cacheAnnotation = method.getAnnotation(CacheAnnotation.class);
        long time = cacheAnnotation.time();
        /**
         * 方法在方法栈内执行,线程安全
         */
        StringBuilder params = new StringBuilder();
        for(Object o: paramObjects){
            //千万别用toString,不然万一那个参数没重写toString方法就等死吧
            params.append(JSON.toJSONString(o));
        }
        Class clazz = joinPoint.getTarget().getClass();
        //防止原参数过长
        String param = MD5Util.encrypt(params.toString());
        String key = clazz.getName()+"::"+method.getName()+"::"+param;
        Object obj = redisUtil.get(key);
        Object ans = null;
        if(obj != null){
            String ansStr = obj.toString();
            ans = JSON.parseObject(ansStr,RestResponse.class);
        } else{
            ans = joinPoint.proceed();
            /**
             * 进行缓存,即使返回的是fail也进行缓存,可以防止缓存穿透
             */
            redisUtil.setex(key,JSON.toJSONString(ans),time);
        }
        /**
         * 如果是点赞或者查看文章的话就直接修改redis
         */
        User user = UserUtil.currentUser();
        if(user != null){
            if(method.equals(ArticleController.class.getMethod("getArticleById", Integer.class))){
                StatisticsUtil.addView((Integer)paramObjects[0], user.getId().toString());
            }
            if(method.equals(ArticleController.class.getMethod("likeArticle",Integer.class))){
                StatisticsUtil.addView((Integer)paramObjects[0],user.getId().toString());
            }
        }
        return ans;
    }
}
